package com.swp.oa.sys.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swp.oa.sys.dao.IAuthDao;
import com.swp.oa.sys.dao.IDepartmentUserDao;
import com.swp.oa.sys.dao.ILoginStateDao;
import com.swp.oa.sys.dao.IRoleAuthDao;
import com.swp.oa.sys.dao.IUserDao;
import com.swp.oa.sys.dao.IUserRoleDao;
import com.swp.oa.sys.dto.domian.UserDto;
import com.swp.oa.sys.pojo.Auth;
import com.swp.oa.sys.pojo.DepartmentUser;
import com.swp.oa.sys.pojo.LoginState;
import com.swp.oa.sys.pojo.RoleAuth;
import com.swp.oa.sys.pojo.User;
import com.swp.oa.sys.pojo.UserExample;
import com.swp.oa.sys.pojo.UserRole;
import com.swp.oa.sys.service.IAuditService;
import com.swp.oa.sys.service.IUserService;
import com.swp.oa.sys.util.Pager;
import com.swp.oa.util.DateUtil;
import com.swp.oa.util.UUIDGenerator;

@Service("userService")
public class UserServiceImpl implements IUserService{

	@Autowired
	private IUserDao userDao;
	@Autowired
	private IUserRoleDao userRoleDao;
	@Autowired
	private IRoleAuthDao roleAuthDao;
	@Autowired
	private IDepartmentUserDao departmentUserDao;
	@Autowired
	private ILoginStateDao loginStateDao;
	@Autowired
	private IAuditService auditService;
	@Autowired
	private IAuthDao authDao;
	

	@Override
	public String save(UserDto userModel) {
		User user = new User();
		user.setUserid(UUIDGenerator.getUUID());
		user.setUsername(userModel.getUserName());
		user.setEmail(userModel.getEmail());
		user.setMobile(userModel.getMobile());
		user.setUpassword(userModel.getPassword());
		user.setRealname(userModel.getRealName());
		user.setGender(userModel.getGender());
		user.setUpassword(userModel.getPassword());
		if(userModel.getStatus() == null){
			user.setUserstatus("1");			
		}else{
			user.setUserstatus("0");			
		}
		user.setCreatedate(new Date());
		user.setUpdatedate(user.getCreatedate());
		user.setVersion(1);
		user.setCreateuser(userModel.getCreateUser());
		//工作路径==第一次添加的用户名
		user.setWorkpath(user.getUsername());
		userDao.insertSelective(user);
		
		DepartmentUser deptUser = new DepartmentUser();
		deptUser.setDepartuserid(UUIDGenerator.getUUID());
		deptUser.setUserid(user.getUserid());
		deptUser.setVersion(1);
		//暂时默认一个用户对应一个部门
		deptUser.setDepartmentid(userModel.getDepartmentId());
		deptUser.setCreatedate(new Date());
		deptUser.setUpdatedate(deptUser.getCreatedate());
		departmentUserDao.insert(deptUser);
		
		
		return user.getUserid();
	}
	@Override
	public boolean saveUserRole(String userId, String roleId) {
		//删除之前的用户角色
		userRoleDao.deleteByUserId(userId);
		
		UserRole userRole = new UserRole();
		userRole.setUserroleid(UUIDGenerator.getUUID());
		userRole.setRoleid(roleId);
		userRole.setUserid(userId);
		userRole.setCreatedate(new Date());
		userRole.setUpdatedate(userRole.getCreatedate());
		userRole.setVersion(1);
		userRoleDao.insert(userRole );
		
		User user = new User();
		user.setUserid(userId);
		user.setUpdatedate(new Date());
		userDao.updateByPrimaryKeySelective(user);
		
		return true;
	}
	@Override
	public boolean deleteByPrimaryKey(String userid) {
		try {
			userDao.deleteByPrimaryKey(userid);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public String deleteUser(String[] userIdArray) {
		String result = "";
		if(userIdArray.length > 0){
			UserExample example = new UserExample();
			List<String> userIds = new ArrayList<String>();
			for (String userId : userIdArray) {
				departmentUserDao.deleteByUserId(userId);
				userRoleDao.deleteByUserId(userId);
				User user = userDao.selectByPrimaryKey(userId);
				if(user != null){
					result += user.getUsername() + "、";
				}
				userIds.add(userId);
			}
			example.or().andUseridIn(userIds);
			userDao.deleteByExample(example);			
		}
		return result;
	}
	@Override
	public boolean update(UserDto userModel) {
		User user = new User();
		user.setUserid(userModel.getId());
		user.setUsername(userModel.getUserName());
		user.setEmail(userModel.getEmail());
		user.setMobile(userModel.getMobile());
		if(userModel.getPassword() != null && !userModel.getPassword().equals("")){
			user.setUpassword(userModel.getPassword());			
		}
		user.setRealname(userModel.getRealName());
		user.setGender(userModel.getGender());
		if(userModel.getStatus() == null){
			user.setUserstatus("1");			
		}else{
			user.setUserstatus("0");			
		}
		user.setUpdatedate(new Date());
		userDao.updateByPrimaryKeySelective(user);
		
		departmentUserDao.deleteByUserId(user.getUserid());
		DepartmentUser deptUser = new DepartmentUser();
		deptUser.setDepartuserid(UUIDGenerator.getUUID());
		deptUser.setUserid(user.getUserid());
		deptUser.setVersion(1);
		//暂时默认一个用户对应一个部门
		deptUser.setDepartmentid(userModel.getDepartmentId());
		deptUser.setCreatedate(new Date());
		deptUser.setUpdatedate(deptUser.getCreatedate());
		departmentUserDao.insert(deptUser);
		return true;
	}
//	@Override
//	public List<UserDto> getUsers() {
//		List<UserDto> userDtos = new ArrayList<UserDto>();
//		List<User> users = userDao.selectAllList();
//		UserDto userDto = null;
//		for (User user : users) {
//			userDto = new UserDto();
//			userDto.setId(user.getUserid());
//			userDto.setNickname(user.getUsername());
//			User ru = userRoleDao.selectRolesByUserId(user.getUserid());
//			if(ru != null){
//				String role =  ru.getRoles().get(0).getRolename();
//				userDto.setRoles(role);
//			}
//			User du = departmentUserDao.selectDepartmentsByUserId(user.getUserid());
//			if(du != null){
//				String dep = du.getDepartments().get(0).getDepartmentname();
//				userDto.setGroups(dep);
//			}
//			userDto.setEmail(user.getEmail());
//			userDto.setPhoneNum(user.getMobile());
//			userDto.setState(user.getUserstatus());
//			userDto.setRealname(user.getRealname());
//			userDto.setPassword(user.getUpassword());
//			userDto.setSalt(user.getPwdsalt());
//			if(user.getCreatedate() != null){
//				userDto.setCreattime(DateUtil.dateFormat(user.getCreatedate()));
//			}
//			userDtos.add(userDto);
//		}
//		return userDtos;
//	}
//	@Override
//	public List<GroupUserDto> getUsersByGroupId(String groupid) {
//		List<GroupUserDto> groupUsers = new ArrayList<GroupUserDto>();
//		Department dep = departmentUserDao.selectUsersByDepartmentId(groupid);
//		
//		List<User> users = dep.getUsers();
//		if(users != null){
//			GroupUserDto groupUser = null;
//			for (User user : users) {
//				groupUser = new GroupUserDto();
//				groupUser.setId(user.getUserid());
//				groupUser.setGroupid(dep.getDepartmentid());
//				groupUser.setNickname(user.getUsername());
//				groupUsers.add(groupUser);
//			}
//		}
//		return groupUsers;
//	}

	@Override
	public boolean existUserName(String userName) {
		User user = userDao.selectByUsername(userName);
		if(user != null){
			return true;
		}
		return false;
	}

	@Override
	public Pager getUserList(int pageIndex, int pageSize, String userName,
			String createdateStart, String createdateEnd,
			String updatedateStart, String updatedateEnd, String[] deptIds) {
		Set<String> userIdSet = new HashSet<String>();
		if (deptIds != null && deptIds.length > 0) {
			List<DepartmentUser> list = departmentUserDao.selectByDepartmentIds(deptIds);
			if(list != null && list.size() > 0){
				for (DepartmentUser departmentUser : list) {
					userIdSet.add(departmentUser.getUserid());
				}
			}else{
				return null;
			}
		}
		List<User> userList = null;
		PageHelper.startPage(pageIndex,pageSize); 
		HashMap<String,String> map = new HashMap<String,String>();
		if (StringUtils.isNotBlank(userName)) {
			userName = "%" + userName + "%";
			map.put("userName", userName);
		}else{
			map.put("userName", null);
		}
		if (StringUtils.isNotBlank(createdateStart)) {
			map.put("createdateStart", createdateStart);
		}else{
			map.put("createdateStart", null);
		}
		if (StringUtils.isNotBlank(createdateEnd)) {
			map.put("createdateEnd", createdateEnd);
		}else{
			map.put("createdateEnd", null);
		}
		if (StringUtils.isNotBlank(updatedateStart)) {
			map.put("updatedateStart", updatedateStart);
		}else{
			map.put("updatedateStart", null);
		}
		if (StringUtils.isNotBlank(updatedateEnd)) {
			map.put("updatedateEnd", updatedateEnd);
		}else{
			map.put("updatedateEnd", null);
		}
		userList = userDao.selectByOption(map);
		if (deptIds != null && deptIds.length > 0) {
				List<User> userList2 = new ArrayList<User>();
				if(userIdSet != null && userIdSet.size() > 0){
					for (User user : userList) {
						if(userIdSet.contains(user.getUserid())){
							userList2.add(user);
						}
					}
					userList = userList2;
				}
		}
		List<UserDto> userModelList = new ArrayList<UserDto>();
		if(userList != null && userList.size() > 0){
			PageInfo page = new PageInfo(userList);
			for (User user : userList) {
				userModelList.add(this.pojoToModel(user));
			}
			Pager pager = new Pager(pageIndex, pageSize, page.getTotal(), userModelList);
			return pager;			
		}
		return null;
	}
	
	@Override
	public UserDto getUserByUserId(String userId) {
		User user = userDao.selectByPrimaryKey(userId);
		if(user != null){
			return this.pojoToModel(user);
		}
		return null;
	}
	@Override
	public UserDto getUserByUserName(String userName) {
		User user = userDao.selectByUsername(userName);
		if(user != null){
			return this.pojoToModel(user);
		}
		return null;
	}
	private UserDto pojoToModel(User user){
		UserDto model = new UserDto();
//		System.out.println(user.getCreatedate());
		model.setCreateDate(DateUtil.dateFormat(user.getCreatedate()));
		model.setCreateUser(user.getCreateuser());
//		model.setDepartmentId(user.get)
		model.setEmail(user.getEmail());
		if(user.getGender() != null && user.getGender().equals("1")){
			model.setGender("男");			
		}else{
			model.setGender("女");
		}
		model.setId(user.getUserid());
		model.setMobile(user.getMobile());
		model.setRealName(user.getRealname());
		if (user.getUserstatus() != null && user.getUserstatus().equals("1")){
			model.setStatus("开启");			
		} else{
			model.setStatus("禁用");			
		}
		model.setUpdateDate(DateUtil.dateFormat(user.getUpdatedate()));
		model.setUpdateUser(user.getUpdateuser());
		model.setUserName(user.getUsername());
		return model;
	}
	@Override
	public String getUserIdByToken(String token) {
		LoginState loginState = loginStateDao.selectByToken(token);
		if(loginState != null){
			return loginState.getUserid();
		}
		return null;
	}
	@Override
	public boolean validatePassword(String userId, String password) {
		User user = userDao.selectByPrimaryKey(userId);
		if(user == null){
			return false;
		}
		if(user.getUpassword().equalsIgnoreCase(password)){
			return true;
		}
		return false;
	}
	@Override
	public void changePassword(String userId, String password) {
		User user = userDao.selectByPrimaryKey(userId);
		if(user == null){
			return;
		}
		user.setUpdatedate(new Date());
		user.setUpassword(password);
		userDao.updateByPrimaryKeySelective(user);
	}
	@Override
	public List<User> getUsersByAuthCode(String code) {
		Auth auth = authDao.selectByCode(code);
		List<RoleAuth> list = roleAuthDao.selectByAuthId(auth.getAuthid());
		if(list == null){
			System.out.println("请定义一个拥有审批权限的角色");
			return null;
		}
		List<String> roleIds = new ArrayList<String>();
		for (RoleAuth roleAuth : list) {
			roleIds.add(roleAuth.getRoleid());
		}
		List<UserRole> userRole = userRoleDao.selectByRoleIds(roleIds);
		if(userRole == null){
			System.out.println("请定义一个用户的角色拥有审批权限");
			return null;
		}
		List<String> userIds = new ArrayList<String>();
		for (UserRole ur : userRole) {
			userIds.add(ur.getUserid());
		}
		UserExample example = new UserExample();
		example.or().andUseridIn(userIds);
		example.setDistinct(true);
		List<User> userList = userDao.selectByExample(example);
//		for (User user : userList) {
//			System.out.println(user.getUserid());
//		}
		return userList;
	}

}
